#ifndef FILES_VALIDATOR_H
#define FILES_VALIDATOR_H

#include <string>
#include <vector>
#include <QString>
#include <QUrl>
#include <QDir>
#include <QAbstractListModel>
#include <optional>

class MediaInspector : public QAbstractListModel
{
    Q_OBJECT

    Q_PROPERTY(int count READ count)

public:

    enum MediaModelRole {
        NameRole = Qt::UserRole + 1,
        TitleImagePathRole,
        LastTimepointRole,
        DurationRole,
        FilenameRole,
    };

    Q_ENUM(MediaModelRole)

    enum SortFlag {
        NameSort,
        LastModifyTimeSort,
        lastTimepointSort,
    };

    Q_ENUM(SortFlag)

    // 构造函数
    explicit MediaInspector(QObject* parent = nullptr);

    /**
     * @brief 打开目录并检索该目录内的所有媒体文件，如果打开成功，稍后可以使用 @see count() 获取该目录下的媒体文件个数
     * @param path 要打开的目录，也可以是一个文件的绝对路径
     * @return 成功返回0， 已经打开了该目录则返回1，
     */
    Q_INVOKABLE int openDir(const QString& path);

    /**
     * @brief 返回当前目录下所有可播放的文件个数
     * @return
     */
    int count();

    int rowCount(const QModelIndex &parent) const override;

    QVariant data(const QModelIndex &index, int role) const override;

    QString stateDesc();

    void setTitleImgDir(QUrl url);

    bool setData(const QModelIndex &index, const QVariant &value, int role) override;

    Q_INVOKABLE QString filename(int i);

    Qt::ItemFlags flags(const QModelIndex &index) const override;

    QHash<int, QByteArray> roleNames() const override;

public slots:
    void sort(SortFlag flag);

    void setLastTimepoint(int i, double sec);

signals:
    void scanFinished();

private:

    QString m_titleImgRootPath;

    struct MediaModel {
        QString name;
        QString titleImagePath;
        double lastTimepoint = 0.0;
        double duration = 0.0;
        QDateTime fileBirthTime;
        QDateTime fileLastModifyTime;
        QString filename;
    };

    // 验证目录下的所有文件
    void previewFiles();

    void openDirAsync();

    // 验证单个文件
    std::optional<MediaModel> validateFile(const QString& filePath);

    QString m_stateDesc;

    std::vector<MediaModel> m_files;

    QDir m_dir;

};

#endif // FILES_VALIDATOR_H
